<template>
  <div class="main">
    <div class="right">
      <img
        class="login_BK"
        src="../../assets/img/login_BK.png"
        alt=""
      >
      <img
        class="logo"
        src="./../../assets/img/logo_yuntong.png"
        alt=""
      >
      <div class="english">Easy-go Operation System</div>
      <div class="title">畅行无忧管理系统</div>
      <!-- <div class="tip">运通汽车集团</div> -->

      <div class="version">V.0.0001</div>
    </div>
    <div class="left">
      <div class="loginTip">欢迎登录</div>
      <a-form
        id="formLogin"
        class="user-layout-login"
        ref="formLogin"
        :form="form"
        @submit="handleSubmit"
      >
        <a-alert
          v-if="isLoginError"
          type="error"
          showIcon
          style="margin-bottom: 24px;"
          :message="errorMsg"
        />
        <a-form-item>
          <a-input
            size="large"
            type="text"
            style="width: 400px; height: 52px;"
            placeholder=""
            v-decorator="[
              'username',
              {initialValue:'',rules: [{ required: true, message: '请输入帐户名或邮箱地址' }, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
            ]"
          />
        </a-form-item>

        <a-form-item>
          <a-input-password
            size="large"
            placeholder=""
            style="width: 400px; height: 52px;"
            v-decorator="[
              'password',
              { initialValue:'',rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'}
            ]"
          />
        </a-form-item>

        <a-form-item>
          <a-checkbox v-decorator="['rememberMe', { valuePropName: 'checked' }]">自动登录</a-checkbox>
        </a-form-item>

        <a-form-item style="margin-top:24px">
          <a-button
            size="large"
            type="primary"
            htmlType="submit"
            style="width: 400px;"
            class="login-button"
            :loading="state.loginBtn"
            :disabled="state.loginBtn"
          >确定</a-button>
        </a-form-item>
      </a-form>

      <two-step-captcha
        v-if="requiredTwoStepCaptcha"
        :visible="stepCaptchaVisible"
        @success="stepCaptchaSuccess"
        @cancel="stepCaptchaCancel"
      ></two-step-captcha>
      <Verify
        @success="capctchaCheckSucc"
        :mode="'pop'"
        :captchaType="'blockPuzzle'"
        :imgSize="{ width: '330px', height: '155px' }"
        ref="verify"
      ></Verify>
    </div>

  </div>
</template>

<script>
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import Verify from '@/components/verifition/Verify'
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
// eslint-disable-next-line no-unused-vars
import md5 from 'md5'
// eslint-disable-next-line no-unused-vars
import { getSmsCaptcha, get2step } from '@/api/login'

export default {
  components: {
    TwoStepCaptcha,
    Verify
  },
  data () {
    return {
      capctchaCheck: false,
      verify: '',
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      errorMsg: '',
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      }
    }
  },
  created () {
    // get2step({ })
    //   .then(res => {
    //     this.requiredTwoStepCaptcha = res.result.stepCode
    //   })
    //   .catch(() => {
    //     this.requiredTwoStepCaptcha = false
    //   })
    // this.requiredTwoStepCaptcha = true
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    // handler
    handleUsernameOrEmail (rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleTabClick (key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },
    capctchaCheckSucc (data) {
      this.capctchaCheck = true
      this.verify = data.captchaVerification
      this.loginForm()
    },
    handleSubmit (e) {
      e.preventDefault()
      this.loginForm()
    },
    loginForm () {
      if (!this.capctchaCheck) {
        this.$refs.verify.show()
        return false
      }
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login
      } = this

      state.loginBtn = true

      const validateFieldsKey = customActiveKey === 'tab1' ? ['username', 'password', 'captcha'] : ['mobile', 'captcha']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          console.log('login form', values)
          const loginParams = { ...values }
          delete loginParams.username
          loginParams[!state.loginType ? 'email' : 'username'] = values.username
          // loginParams.password = md5(values.password)
          const captchaVO = { captchaVerification: this.verify }
          loginParams.captchaVO = captchaVO
          Login(loginParams)
            .then(res => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
              this.capctchaCheck = false
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    getCaptcha (e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state
      } = this

      validateFields(['mobile'], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = this.$message.loading('验证码发送中..', 0)
          getSmsCaptcha({ mobile: values.mobile })
            .then(res => {
              setTimeout(hide, 2500)
              this.$notification['success']({
                message: '提示',
                description: '验证码获取成功，您的验证码为：' + res.result.captcha,
                duration: 8
              })
            })
            .catch(err => {
              setTimeout(hide, 1)
              clearInterval(interval)
              state.time = 60
              state.smsSendBtn = false
              this.requestFailed(err)
            })
        }
      })
    },
    stepCaptchaSuccess () {
      this.loginSuccess()
    },
    stepCaptchaCancel () {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    loginSuccess (res) {
      if (res.code === 0) {
        this.$router.push({ name: 'dashboard' }, () => {
          this.$notification.success({
            message: '欢迎',
            description: `${timeFix()}，欢迎回来`
          })
        })
        this.isLoginError = false
      } else {
        this.$refs.verify.refresh()
        this.requestFailed(res)
      }
    },
    requestFailed (err) {
      this.isLoginError = true
      this.errorMsg = ((err.response || {}).data || {}).msg || err.msg || '请求出现错误，请稍后再试'
      this.$notification['error']({
        message: '错误',
        description: this.errorMsg,
        duration: 4
      })
    }
  }
}
</script>

<style lang="less" scoped>
.main {
  display: flex;
  flex-direction: row;
  justify-content: center;
  width: 100%;
  height: 100vh;
  .left {
    min-width: 520px;
    padding-left: 60px;
    padding-top: 212px;
    .loginTip {
      font-family: 'Microsoft YaHei';
      font-size: 42px;
      color: #333333;
      margin-bottom: 44px;
    }
  }
  .right {
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding-left: 140px;
    min-width: 750px;
    flex: 1;
    width: 100%;
    height: 100%;
    background: transparent;
    background-image: radial-gradient(37% 146%, #0022bf 9%, rgba(141, 72, 178, 0) 100%);
    .logo {
      width: 208px;
      height: 48px;
      margin-bottom: 48px;
      position: absolute;
      top: 140px;
      right: 120px;
    }
    .title {
      font-family: 'Microsoft YaHei';
      font-size: 20px !important;
      color: #ffffff;
      font-weight: 200;
      position: absolute;
      right: 120px;
      bottom: 200px;
    }
    .english {
      width: 668px;
      position: absolute;
      right: 100px;
      font-size: 84px;
      color: #ffffff;
    }
    .tip {
      font-family: 'Microsoft YaHei';
      font-size: 20px;
      color: #ffffff;
      position: absolute !important;
      right: 120px !important;
      bottom: 180px !important;
    }
    .version {
      font-family: MicrosoftYaHeiUILight;
      font-size: 20px;
      color: #ffffff;
      letter-spacing: 0;
      font-weight: 200;
      position:absolute;
      bottom: 160px !important;
      right: 120px !important;
    }
    .login_BK {
      position: absolute;
      top: 0;
      left: 0;
      z-index: -1;
      width: 100%;
      height: 100%;
    }
  }
}
.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    height: 64px;
    background-image: linear-gradient(135deg, #227fe6 0%, #8d48b2 100%);
    border-radius: 6px;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>
